﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Assets.Scripts.LDS;
using System.IO;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif

[ExecuteInEditMode]

public class TextDialog : MonoBehaviour
{
    public Button myButton;
    public InputField inputField;
    public Text logField;


    public bool LDSEnable = true;
    static public Text logText;

    // Start is called before the first frame update
    void Start()
    {
        logText = logField.GetComponent<Text>();
        Debug.Log("You Start!");
        Button btn = myButton.GetComponent<Button>();
        btn.onClick.AddListener(OnButtonProcess);

        ScriptProcessor.Instance.clearResult();
        if (LDSEnable)
        {
            Scene _scene = Scene.Instance;
            ScriptProcessor.Instance.LDSEnable = true;
        }

        logClear();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return))
        {
            OnButtonProcess();
        }
    }


    public void OnButtonProcess()
    {
        ScriptProcessor.Instance.Process(inputField.GetComponent<InputField>().text);
    }

    static public bool isLogUpdated = false;
    
    public static void logClear()
    {
        logText.GetComponent<Text>().GetComponent<Text>().text = "";
        isLogUpdated = true;
    }
    public static void textDebug(string stc, bool error = false)
    {
        if (error)
        {
            logText.GetComponent<Text>().GetComponent<Text>().text += "\n" + "Error: " + stc;
            Debug.LogError(stc);
            isLogUpdated = true;
        }
        else
        {
            logText.GetComponent<Text>().GetComponent<Text>().text += "\n" + stc;
            Debug.Log(stc);
            isLogUpdated = true;
        }
    }

#if UNITY_EDITOR
    [CustomEditor(typeof(TextDialog))]
    public class TextDialog_Editor : Editor
    {
        public TextDialog Target;

        private void Awake()
        {
            Target = (TextDialog)target;
        }


        public override void OnInspectorGUI()
        {

            Undo.RecordObject(Target, Target.name);

            base.OnInspectorGUI();

            if (Utility.GUIButton("Process", UltiDraw.DarkGrey, UltiDraw.White))
            {
                string script;
                using (StreamReader sr = new StreamReader("script.txt"))// .xml
                {
                    script = sr.ReadToEnd();
                }
                ScriptProcessor.Instance.Process(script);
            }

            if (GUI.changed)
            {
                EditorUtility.SetDirty(Target);
            }

        }
    }
#endif


}